package com.yuanfeng.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanfeng.base.dto.ModularizationdDTO;
import com.yuanfeng.base.entity.BaseShopModularizationdEntity;
import com.yuanfeng.base.feign.BusinessClient;
import com.yuanfeng.base.mapper.BaseShopModularizationdMapper;
import com.yuanfeng.base.service.BaseShopModularizationdService;
import com.yuanfeng.base.vo.ModularizationdGoodsVO;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.Json.JsonUtils;
import com.yuanfeng.commoms.util.*;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.shop.GdsShopDetailResultVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Service
public class BaseShopModularizationdServiceImpl extends ServiceImpl<BaseShopModularizationdMapper, BaseShopModularizationdEntity>
    implements BaseShopModularizationdService{

    @Autowired
    private BaseModularizationdServiceImpl baseModularizationdServiceImpl;

    @Autowired
    private BusinessClient businessClient;

    @Override
    public ResponseResult bottomNavigation(ModularizationdDTO param) {
        try {

            UserInfoVO userInfo =null;
            String userInfoStr = RedisUtil.get(YFConfig.YF_USER_TOKEN_USER+param.getToken());
            if(StringUtils.isNotBlank(userInfoStr)) {
                userInfo = ParseTokenUtils.getUserInfoByToken(param.getToken());
                Integer shopId = Integer.valueOf(userInfo.getShopId());
                if (shopId == null) {
                    return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
                }
                param.setShopId(shopId);
                param.setPageType(1);
                param.setPageStart(1);
                param.setPageIsIndex(3);

                if (null == param.getPageId()) { //添加或修改

                    String UUidPageId= UUIDUtil.getUUID1();
                    param.setPageId(Integer.valueOf(UUidPageId.substring(0,7)));
                    int result = this.baseMapper.add(param);
                    if (0 == result) {
                        return ResponseResult.fail(BizCodeEnume.OPERATION_FAILED);
                    }
                    return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
                } else {
                    int result = this.baseMapper.updateInfo(param);
                    if (0 == result) {
                        return ResponseResult.fail(BizCodeEnume.OPERATION_FAILED);
                    }
                    return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
                }
            }else{
                return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(e.getMessage());
        }
    }

    @Override
    public ResponseResult querybottomNavigation(Map<String, Object> param) {
        UserInfoVO userInfo =null;;
        String userInfoStr = RedisUtil.get(YFConfig.YF_USER_TOKEN_USER+param.get("token").toString());
        if (StringUtils.isNotBlank(userInfoStr)) {
            userInfo = ParseTokenUtils.getUserInfoByToken(param.get("token").toString());
            Integer shopId = Integer.valueOf(userInfo.getShopId());
            HashMap<String, Object> map = new HashMap();

            BaseShopModularizationdEntity list = this.baseMapper.selectOne(new LambdaQueryWrapper<BaseShopModularizationdEntity>()
                                                .eq(BaseShopModularizationdEntity::getShopId,shopId)
                                                .eq(BaseShopModularizationdEntity::getPageIsIndex,3));
            if (list != null) {
                map.put("pagedata", list.getPageData());
                map.put("pageId", list.getPageId());

                return ResponseResult.success(map);
            } else {
                return ResponseResult.fail(BizCodeEnume.SELECT_DATA_NULL);
            }
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
    }

    @Override
    public ResponseResult modularizationdUpdateIndex(Map<String, Object> map) {
        if(null == map && null == map.get("shopId")){
            return ResponseResult.fail(2,"shopId不能为空");
        }
        try {
            //查询首页数据
            ModularizationdDTO modularizationdParam = this.baseMapper.selectModularizationdByStart((Integer)map.get("shopId"));
            List<ModularizationdGoodsVO> modularizationdGoodsParams = queryModularizationdGoodsInfo(modularizationdParam.getGoodsAllIdJson());
            modularizationdParam.setGoodsList(modularizationdGoodsParams);
            GdsShopDetailResultVO shopBaseEntity = businessClient.queryShopinfoByShopId((Integer) map.get("shopId"));
            modularizationdParam.setShopName(shopBaseEntity.getShopName());
            modularizationdParam.setShopCollect(shopBaseEntity.getShopCollect());
            modularizationdParam.setShopLogo(shopBaseEntity.getShopLogo());
            return ResponseResult.success(modularizationdParam);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.fail(2,"当前商家没有设置首页");
    }

    @Override
    public ResponseResult ModularizationdAddOrUPdate(ModularizationdDTO param) {
        Integer result = null;
        try {
            if(null == param.getPageType()){
                param.setPageType(0);
            }
            UserInfoVO userInfo =null;
            String userInfoStr =RedisUtil.get(YFConfig.YF_USER_TOKEN_USER+param.getToken());
            if(StringUtils.isNotBlank(userInfoStr)) {
                userInfo = ParseTokenUtils.getUserInfoByToken(param.getToken());

                if (userInfo.getShopId() == null) {
                    return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
                }
                Integer shopId = Integer.valueOf(userInfo.getShopId());
                param.setShopId(shopId);

                if (null == param.getPageId()) { //添加或修改
                    if (null != param.getGoodsAllId() && param.getGoodsAllId().size() > 0) {
                        param.setGoodsAllIdJson(JsonUtils.toString(param.getGoodsAllId()));
                    }
                    if (null != param.getPageIsIndex() && 2 == param.getPageIsIndex()) {//判断是否是二级页面
                        param.setPageStart(0);
                    } else {
                        param.setPageStart(0);
                    }
                    String UUidPageId=UUIDUtil.getUUID1();
                    param.setPageId(Integer.valueOf(UUidPageId.substring(0,7)));
                    result =  this.baseMapper.add(param);
                    if (0 == result) {
                        return ResponseResult.fail(BizCodeEnume.OPERATION_FAILED);
                    }
                    return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
                } else {
                    if (null != param.getGoodsAllId() && param.getGoodsAllId().size() > 0) {
                        param.setGoodsAllIdJson(JsonUtils.toString(param.getGoodsAllId()));
                    }
                    result = this.baseMapper.updateInfo(param);
                    if (0 == result) {
                        return ResponseResult.fail(BizCodeEnume.OPERATION_FAILED);
                    }
                    return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
                }
            }else{
                return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(e.getMessage());
        }

    }

    @Override
    public ResponseResult queryModularizationdAll(ModularizationdDTO param) {
        try {
            Integer count = null;
            Map<String,Object> map = new HashMap<>();

            UserInfoVO userInfo =null;
            //if(StringUtils.isNotBlank(param.getToken())){
            String userInfoStr =RedisUtil.get(YFConfig.YF_USER_TOKEN_USER+param.getToken());
            if(StringUtils.isNotBlank(userInfoStr)){
                userInfo = ParseTokenUtils.getUserInfoByToken(param.getToken());

                if(userInfo.getShopId()==null ){
                    return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
                }
                Integer shopId = Integer.valueOf(userInfo.getShopId());
                param.setShopId(shopId);

                Map data= ParseMapUtils.beanToMap(param);
                IPage<BaseShopModularizationdEntity> page=this.baseMapper.queryModularizationdAll(new Query<BaseShopModularizationdEntity>().getPage(data),
                        param);

                if(null != param.getPageIsIndex() && 2 == param.getPageIsIndex()){//判断是否是二级页面
                    if(page.getRecords().size()>0){
                        for (BaseShopModularizationdEntity modularizationdParam : page.getRecords()) {
                            if(null != modularizationdParam.getPageStart() && 0 == modularizationdParam.getPageStart()){//判断二级页面是否开启 1 开启 0 关闭
                                modularizationdParam.setPageUrl("/store/shopDiy/shopDiy?pageId="+modularizationdParam.getPageId());
                            }
                        }
                    }
                }
                return  ResponseResult.success(PageUtils.getPage(page));
            }else{
                return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(e.getMessage());
        }
    }

    @Override
    public ResponseResult queryModularizationdShopById(ModularizationdDTO param) {
        if(null == param.getPageId()){
            return ResponseResult.fail(BizCodeEnume.MISSING_PARAMETER.getCode(),BizCodeEnume.MISSING_PARAMETER.getMsg());
        }
        ModularizationdDTO  modularizationdParam =  this.baseMapper.queryModularizationdById(param);
        List<ModularizationdGoodsVO> modularizationdGoodsParams = queryModularizationdGoodsInfo(modularizationdParam.getGoodsAllIdJson());
        modularizationdParam.setGoodsList(modularizationdGoodsParams);
        return ResponseResult.success(modularizationdParam);
    }

    @Override
    public ResponseResult modularizationdDelete(ModularizationdDTO param) {
        if(null != param && null != param.getToken()){
            UserInfoVO userInfo =null;
            String userInfoStr =RedisUtil.get(YFConfig.YF_USER_TOKEN_USER+param.getToken());
            userInfo = ParseTokenUtils.getUserInfoByToken(param.getToken());
            if(userInfo.getShopId()==null ){
                return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
            }
            Integer shopId = Integer.valueOf(userInfo.getShopId());

            Integer result = null;
            try {
                if(null == param.getPageId()){
                    return ResponseResult.fail(0, "pageid 不能为null");
                }
                result =  this.baseMapper.deleteById(param.getPageId());
                if(0 == result){
                    return ResponseResult.fail(BizCodeEnume.DELETE_ERROR);
                }
                return ResponseResult.fail(BizCodeEnume.DELETE_SUCCESS);
            } catch (Exception e) {
                e.printStackTrace();
                return ResponseResult.fail(e.getMessage());
            }

        }
        return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
    }

    @Override
    public ResponseResult modularizationdUpdateStart(ModularizationdDTO param) {
        if(null != param && null != param.getToken()) {
            UserInfoVO userInfo =null;
            String userInfoStr =RedisUtil.get(YFConfig.YF_USER_TOKEN_USER+param.getToken());
            userInfo = ParseTokenUtils.getUserInfoByToken(param.getToken());
            if(userInfo.getShopId()==null ){
                return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
            }
            Integer shopId = Integer.valueOf(userInfo.getShopId());

            Integer result = null;
            Integer rr = null;
            try {
                if (null == param.getPageId()) {
                    return ResponseResult.fail(0, "pageid 不能为null");
                }
                if (null == param.getPageStart()) {
                    return ResponseResult.fail(0, "pageStart 不能为null");
                }
                this.baseMapper.update(null,new LambdaUpdateWrapper<BaseShopModularizationdEntity>()
                                .eq(BaseShopModularizationdEntity::getPageIsIndex,"1")
                                .set(BaseShopModularizationdEntity::getPageStart,"2"));// 将其他的设置为首页的页面 取消设置
                result =  this.baseMapper.update(null,new LambdaUpdateWrapper<BaseShopModularizationdEntity>()
                        .eq(BaseShopModularizationdEntity::getPageId,param.getPageId())
                        .set(BaseShopModularizationdEntity::getPageStart,param.getPageStart()));
                if (0 == result) {
                    return ResponseResult.fail(BizCodeEnume.UPDATE_ERROR);
                }
                return ResponseResult.success(BizCodeEnume.UPDATE_SUCCEEDED);
            } catch (Exception e) {
                e.printStackTrace();
                return ResponseResult.fail(e.getMessage());
            }
        }
        return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
    }

    public List<ModularizationdGoodsVO> queryModularizationdGoodsInfo(String goodsAllIdJson){
        List<ModularizationdGoodsVO> list = new ArrayList<>();
        if(null == goodsAllIdJson){
            return null;
        }
        List<String> goodsAllIdJsons = JsonUtils.string2Obj(goodsAllIdJson, List.class, String.class);
        for (String goodsId : goodsAllIdJsons) {
            //查询商品 价格 销量
            ModularizationdGoodsVO  modularizationdGoodsParam = this.baseMapper.queryModularizationdGoodsInfo(goodsId);
            Map<String,Object> activityMap = baseModularizationdServiceImpl.dealActivityStatus(Integer.parseInt(goodsId));
            if(null == modularizationdGoodsParam){
                modularizationdGoodsParam = new ModularizationdGoodsVO();
                modularizationdGoodsParam.setGoodsStart(2);//商品状态 1 上架 2 下架
                modularizationdGoodsParam.setGoodsId(Integer.valueOf(goodsId));//商品状态 1 上架 2 下架
            }else{
                modularizationdGoodsParam.setGoodsStart(1);//商品状态 1 上架 2 下架
            }
            if(null != activityMap.get("activityStatus") && 1 == (Integer) activityMap.get("activityStatus")){
                modularizationdGoodsParam.setActivityStatus(1);
                if(null != activityMap.get("activityPrice")){
                    modularizationdGoodsParam.setCommonPrice((BigDecimal) activityMap.get("activityPrice"));
                    modularizationdGoodsParam.setStartTime(activityMap.get("startTime").toString());
                    modularizationdGoodsParam.setEndTime( activityMap.get("endTime").toString());
                }
            }else {
                modularizationdGoodsParam.setActivityStatus(2);
            }
            list.add(modularizationdGoodsParam);
        }
        return list;
    }
}




